package io.a.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class EchoHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 处理接收到的消息
        ByteBuf in = (ByteBuf) msg;
        System.out.println(ByteBufUtil.prettyHexDump(in));
        System.out.println("Server received: " + in.toString(io.netty.util.CharsetUtil.UTF_8));

        // 将接收到的消息写回给客户端
        ctx.write(in);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        // 当所有数据都被读取完成后，刷新缓冲区并关闭连接
        ctx.writeAndFlush(io.netty.buffer.Unpooled.EMPTY_BUFFER);
//        ctx.writeAndFlush(io.netty.buffer.Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 处理异常
        cause.printStackTrace();
        ctx.close();
    }


}